package com.ttl.sbgl.loginback.service.serviceImpl;

import com.ttl.sbgl.loginback.entity.User;
import com.ttl.sbgl.loginback.repository.UserRepository;
import com.ttl.sbgl.loginback.service.UserService;
import com.ttl.sbgl.loginback.utils.MD5Util;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {
//因为要用到UserService中的方法，所以先通过@Resource注解帮助我们实例化UserDao对象
@Resource
private UserRepository userRepository;
    @Override
    public User loginService(String name, String password) {
        //1.查找用户是否存在
        User user = userRepository.findByName(name);
        if (user == null)
        {
            //2.用户不存在直接返回
           return null;
        }
        // 3. 密码匹配
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(password, user.getPassword())) {
            // 4. 密码匹配时清除敏感信息
            user.setPassword("");
            return user;
        } else {
            // 5. 密码不匹配
            return null;
        }
    }


    @Override
    public User registerService(User user) {
        if(userRepository.findByName(user.getName())!=null){
            return null;
        }
        else {

            String rawpassword = user.getPassword();
////            MD5加密
//            String md5password = DigestUtils.md5DigestAsHex(rawpassword.getBytes());
//            user.setPassword(md5password);

            // 更加安全方式：使用 BCrypt 哈希密码
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String hashedPassword = encoder.encode(rawpassword); // 自动加盐 + 多次迭代
            user.setPassword(hashedPassword);

            User newUser = userRepository.save(user);
            newUser.setPassword("");
            return  newUser;
        }

    }
    @Override
    public boolean changePasswordService(String name, String oldPassword, String newPassword) {
        User user = userRepository.findByName(name);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(oldPassword, user.getPassword())) {
            user.setPassword(encoder.encode(newPassword));
            userRepository.save(user);
            return true;
        }
        return false;

    }
}
